package com.pingxx.demo.integration;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.zookeeper.lock.ZookeeperLockRegistry;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Slf4j
@Component
public class ZookeeperLockSample {

    private  ZookeeperLockRegistry zookeeperLockRegistry;

    public void process(String orderNo) {
        Lock lock = zookeeperLockRegistry.obtain("orderNo:" + orderNo);
        boolean result = false;
        try {
            result = lock.tryLock(1000L, TimeUnit.MICROSECONDS);
            if (result) {
                //todo
                log.info("working....");
            }
        } catch (InterruptedException e) {
            //
            log.error("lock error", e);
        } finally {
            if (result) {
                lock.unlock();
            }
        }
    }

    public ZookeeperLockRegistry getZookeeperLockRegistry() {
        return zookeeperLockRegistry;
    }

//    @Autowired
    public void setZookeeperLockRegistry(ZookeeperLockRegistry zookeeperLockRegistry) {
        this.zookeeperLockRegistry = zookeeperLockRegistry;
    }

}
